<?php

namespace App\Livewire\Components;

use Carbon\Carbon;
use Livewire\Component;
use App\Models\Article;
use App\Models\ArticleAction as ArticleActionModel;

class ArticleAction extends Component
{
    public $article_id;

    public function mount($article_id)
    {
        $this->article_id = $article_id;
    }

    public function like()
    {
        if ($this->getRecord(request()->ip(), 'like')) {
            $articleId = $this->article_id;
            $article = Article::query()->find($articleId);
            $article->increment('like_quantity');
            ArticleActionModel::query()->create([
                'article_id' => $articleId,
                'ip'         => request()->ip(),
                'type'       => 'like',
            ]);
            $this->js("alert('感谢您的点赞!')");
        }else{
            $this->js("alert('已经点过赞了!')");
        }
    }

    public function getRecord($ip, $type)
    {
        $record = ArticleActionModel::query()
            ->where('ip', $ip)
            ->where('type', $type)
            ->whereDay('created_at', Carbon::today())
            ->first();
        if (is_null($record)) {
            return true;
        }
    }

    public function render()
    {
        return view('livewire.components.article-action');
    }
}
